package com.lrs.java.designPattern.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy implements InvocationHandler {

	IService service = null;

	public Object createProxy(IService service) {
		this.service = service;
		IService proxy =  (IService) Proxy.newProxyInstance(service.getClass()
				.getClassLoader(), service.getClass().getInterfaces(), this);
		
		return proxy;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {

		System.out.println("doBefore");
		Object obj = method.invoke(service, args);
		System.out.println("doAfter");
		return obj;
		
	}

	public static void main(String[] args) {
		DynamicProxy dp = new DynamicProxy();
		IService service = (IService)dp.createProxy(new ServiceImp());
		service.doSomething1();
		service.doSomething2();
	}
}
